import axios from 'axios'
import { notification } from 'ant-design-vue'
import { UseUIStore } from '@/@base/store/UI'
import { GetToken } from './auth'


const server = axios.create({
    baseURL: import.meta.env.VITE_APP_API_HOST,
    timeout: 90 * 1000
})
server.defaults.headers.post['Content-Type'] = 'spplication/json';

server.interceptors.request.use(config => {
    const token = GetToken();
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
    }
    return config
}, error => {
    return Promise.reject(error)
})

server.interceptors.response.use(response => {
    return response.data
}, error => {
    if (!error.response) {
        return Promise.reject(error)
    };

    if (error.response.status == 403) {
        notification.error({ message: 'Service Error 403', description: '参数错误，请检查参数信息', });
    } else if (error.response.status == 400) {
        notification.error({ message: 'Service Error 400', description: '参数错误，请检查参数信息', });
    } else if (error.response.status == 404) {
        notification.error({ message: 'Service Error 404', description: '未找到接口，请检查链接地址', });
    } else if (error.response.status == 500) {
        notification.error({ message: 'Service Error 500', description: '服务器出现错误', });
    } else if (error.response.status == 502) {
        notification.error({ message: 'Service Error 502', description: '服务器响应出现错误', });
    } else {
        notification.error({ message: 'Service Error' + error.response.status, description: '链接异常，请检查错误信息', });
    }
    return Promise.reject(error)
})



const http = function (options) {
    var _url = options.url;
    var _params = JSON.parse(JSON.stringify(options.params));
    _url = _url.replace(/\{\w+\}/g, function (i) {
        var _src = i.replace('{', '').replace('}', '');
        if (_params.hasOwnProperty(_src)) {
            var _value = _params[_src];
            delete _params[_src];
            return _value;
        }
    });
    return server({
        ...options.config,
        method: options.type,
        url: _url,
        params: _params,
        data: options.data,
    })
}


export default http;
